//引入config
import config from '../config/index.js';
import request from '../utils/request.js'
import { getAccessToken } from '../api/wechat/index.js'
import fs from 'fs'
import path from 'path';
import { fileURLToPath } from 'url';
import { deleteMenus } from '../api/menus/index.js'
import { createMenus } from '../api/menus/index.js'
import { menus } from '../wechat/menus.js'
const __dirname = path.dirname(fileURLToPath(import.meta.url));



const { appID, appSecret, token } = config;
//定义一个处理Access token的类
class AccessToken {
    constructor() {
    }

    //获取access token
    async getAccessToken(appID, appSecret) {
        //获取access token
        const res = await getAccessToken(appID, appSecret);
        return res;
    }

    //保存access token
    async saveAccessToken() {
        //获取access token
        const res = await this.getAccessToken(appID, appSecret)
        let { expires_in } = res;
        res.expires_in = Date.now() + (expires_in - 300) * 1000; // 提前5分钟刷新
        // console.log(res);  //res {access_token: '79_ANO3uxpTxtiVX-3OFupO7IFyGmKO6X3MgouSthg…5pvqeZVLSjwyrFB4z_VvFAqFhsotYOgCVQfAIAIBW', expires_in: 7200}
        return new Promise((resolve, reject) => {
            //将access token写入文件
            fs.writeFileSync(__dirname + '/access_token.json', JSON.stringify(res), 'utf8', (err) => {
                if (err) {
                    reject(err);
                }
                resolve(res);
            });
        })
    }

    //读取access token
    async readAccessToken() {
        return new Promise(async (resolve, reject) => {
            //判断文件是否存在
            if (fs.existsSync(__dirname + '/access_token.json')) {
                const data = fs.readFileSync(__dirname + '/access_token.json', 'utf8');
                resolve(JSON.parse(data));
            } else {
                //不存在则创建文件
                await this.saveAccessToken()
                    .then(async () => {
                        //重新读取文件
                        await this.readAccessToken()
                    })
                    .catch(err => {
                        reject(err);
                    })
            }
        })
    }

    //验证access token的时效性
    async checkAccessToken(data) {
        if (!data.access_token || !data.expires_in) {
            return false;
        }
        return Date.now() < data.expires_in;
    }

    //获取没有过期的access token
    async getNoExpiredAccessToken() {
        //首先在本地文件中读取access token
        const data = await this.readAccessToken();
        if (await this.checkAccessToken(data)) {
            return data.access_token;
        } else {
            //如果过期则重新获取
            await this.saveAccessToken()
                .then(async () => {
                    const res = await this.readAccessToken();
                    if (res) {
                        this.getNoExpiredAccessToken();
                    } else {
                        console.log('读取文件失败');
                    }
                })
                .catch((err) => {
                    console.log('读取文件失败', err);
                });

        }
    }
}


const wechat = new AccessToken();

async function test() {
    // const res = await wechat.getAccessToken(appID, appSecret);
    // console.log('res', res);
    // const res = await wechat.saveAccessToken();
    // const res = await wechat.readAccessToken();
    // console.log('res', res.access_token);
    //当前1711980209843
    //1712043512103
    //1712043512103
    //1712043512103
    //1712301595559
    const res = await wechat.getNoExpiredAccessToken();
    const result = await deleteMenus(res);
    console.log(result);
    const data = await createMenus(res, menus);
    console.log(data);
}
test()

